package org.ezplatform.office.questionnaire.service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.questionnaire.dao.QuestionnaireAnswerDao;
import org.ezplatform.office.questionnaire.dao.QuestionnaireTopicDao;
import org.ezplatform.office.questionnaire.dao.QuestionnaireTopicOptionsDao;
import org.ezplatform.office.questionnaire.dao.QusetionnaireAnswerStatusDao;
import org.ezplatform.office.questionnaire.entity.Questionnaire;
import org.ezplatform.office.questionnaire.entity.QuestionnaireAnswer;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopic;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopicOptions;
import org.ezplatform.office.questionnaire.util.JsonUtil;
import org.ezplatform.office.questionnaire.util.QuestionnaireUtils;
import org.ezplatform.util.CacheUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <br> 问卷题目接口类
 * <br> 创建时间 2017-11-23
 * @author wujs
 * @version 1.0
 * 
*/

@Service("questionnaireTopicService")
@Transactional
public class QuestionnaireTopicService extends BaseService<QuestionnaireTopic,String>{
	
	private final static Logger LOGGER = LoggerFactory.getLogger(QuestionnaireTopicService.class);
	
	public final static String QUES_TYPE="quesType";
	public final static String QUES_TOPIC="quesTopic";
	public final static String QUES_TOPIC_OPT="quesTopicOpt";
	
	@Autowired
	@Qualifier("questionnaireTopicDao")
	private QuestionnaireTopicDao topicDao;
	
	@Autowired
	@Qualifier("questionnaireTopicOptionsDao")
	private QuestionnaireTopicOptionsDao optionDao;
	
	@Autowired
	@Qualifier("qusetionnaireAnswerStatusDao")
	private QusetionnaireAnswerStatusDao answerStatusDao;
	
	@Autowired
	@Qualifier("questionnaireAnswerDao")
	private QuestionnaireAnswerDao answerDao;
	
	@Autowired
	private AttachmentUtilsService attchService;
	@Lazy
	@Autowired
	private QuestionnaireAnswerService answerService;
	@Lazy
	@Autowired
	private QuestionnaireService quesService;
	
	@Autowired
	private PopUserScopeUtilService popService;
	
	@Autowired
	private UserApiService userApiService;
	@Lazy
	@Autowired
	private QuestionnaireTopicOptionsService optionService;
	@Lazy
	@Autowired
	private QuestionnaireService questionnaireService;
	@Lazy
	@Autowired
	private QuestionnaireAnswerStatusService questionnaireAnswerStatusService;
	
	@Autowired
	private QuesCache quesCache;
	
	@Override
	protected JpaBaseDao<QuestionnaireTopic, String> getEntityDao() {
		return topicDao;
	}
	
	/**
	 * 获取要保存的题目
	 * @param map 题目实体map形式
	 * @param quesitionnaireId 问卷ID
	 * @param topicType 题目类型：sinselect-单选、multiselect-多选、check-下拉、scale-量表、mulscale-矩阵量表、answer-问答、field-附件、paging-分页、illustrate-说明
	 * @return 题目实体集合
	 */
	public QuestionnaireTopic getSaveTopicInfo(Map<String,Object> map,String quesitionnaireId,String topicType){
		QuestionnaireTopic topic = new QuestionnaireTopic();
		String topicName = (String) map.get("topic");
		String topicTxt = (String) map.get("topicTxt");
		String topicNo = (String) map.get("topicNo");
		String times = (String) map.get("times");
		if(times != null && !ValidateUtils.validateId(times)) {
            throw new ValidationException("非法参数");
        }
		/*单选、多选、下拉、量表、矩阵量表有是否计分选项*/
		if("sinselect".equals(topicType) || "trueOrFalse".equals(topicType) || "multiselect".equals(topicType) || "check".equals(topicType) || "scale".equals(topicType) || "mulscale".equals(topicType)){
			String isScore = (String) map.get("isScore");
			topic.setIsScore(isScore);
		}
		if("illustrate".equals(topicType) || "paging".equals(topicType)){
			topicNo="";
		}else if("answer".equals(topicType) || "fillInBlanks".equals(topicType)) {
			topic.setTopicSetting(StringUtils.null2String(map.get("topicSetting")));
		}else{
			Map<String,Object> topicMap = (Map<String, Object>) map.get("topicSetting");
			String topicSetting =JsonUtil.mapToJson(topicMap);
			topic.setTopicSetting(topicSetting);
		}
		int orderNo = 0;
		if(map.get("dataSortNo") != null) orderNo = Integer.parseInt(map.get("dataSortNo").toString());
		topic.setTopicName(topicName);
		topic.setTopicNameTxt(topicTxt);
		topic.setTopicNo(topicNo);
		topic.setOrderNo(orderNo);
		topic.setTopicType(topicType);
		topic.setQuestionnaireId(quesitionnaireId);
		topic.setTimes(times);
		String id = UuidUtils.UUID();
		topic.setId(id);
		return topic;
	}

	/**
	 * 根据问卷ID删除问卷题目
	 * @param quesId 问卷ID
	 * @return 删除成功返回true
	 */
	public boolean deleteTopicByQuesId(String quesId){
		topicDao.deleteTopicByQuesId(quesId);
		return true;
	}
	
	/**
	 * 根据问卷ID删除问卷题目
	 * @param list 问卷ID集合
	 * @return 删除成功返回true
	 */
	public boolean deleteTopicByQuesId(List<String> list){
		topicDao.deleteTopicByQuesId(list);
		return true;
	}
	
	/**
	 * 根据问卷查询题目
	 * @param quesId 问卷ID
	 * @return 题目id集合
	 */
	public List<String> getTopicIdByQeusId(String quesId){
		return topicDao.getTopicIdByQeusId(quesId);
	}
	
	/**
	 * 根据问卷查询题目
	 * @param list 问卷ID集合
	 * @return 题目id集合
	 */
	public List<String> getTopicIdByQeusId(List<String> list){
		return topicDao.getTopicIdByQeusId(list);
	}
	
	/**
	 * 获取问卷题目信息
	 * @param quesId 问卷ID
	 * @param userId 用户ID
	 * @param token 系统参数：TOKEN
	 * @param isUsedCache 如果是答卷接口访问就使用缓存，如果是设计接口访问不使用缓存
	 * @return 问卷题目实体集合
	 */
	public List<QuestionnaireTopic> getTopicOPtionInfo(String quesId,String userId,String token,boolean isUsedCache){
		List<QuestionnaireTopic> list = new ArrayList<>();
//		long time=System.currentTimeMillis();
		String quesType = isUsedCache?(String)quesCache.get(quesId+QuestionnaireTopicService.QUES_TYPE):null;
		if(quesType==null) {
			Questionnaire ques=quesService.findOne(quesId);
			if(isUsedCache) {
				quesCache.set(quesId+QuestionnaireTopicService.QUES_TYPE, ques.getType());
			}
		}
		boolean isExam=true;
		if(!"questionnaireExam".equals(quesType)) {
			isExam=false;
		}
		
		List<QuestionnaireTopic> topicList = isUsedCache?(List<QuestionnaireTopic>)quesCache.get(quesId+QuestionnaireTopicService.QUES_TOPIC):null;
		if(topicList==null||topicList.size()==0) {
			topicList= topicDao.getTopicByQeusId(quesId);
			if(isUsedCache) {
				quesCache.set(quesId+QuestionnaireTopicService.QUES_TOPIC, topicList);
			}
		}
//		LOGGER.error(userId+":user:op1:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
		String flag = "0";
		int pageIndex = 1;
		int answerNum = 1;
		if(!isExam) {
			answerNum = answerStatusDao.getAnswerNumByQuesId(quesId);//提交答卷人数
		}
		
//		LOGGER.error(userId+":user:op2:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
		List<QuestionnaireTopicOptions> optionsListTemp = isUsedCache?(List<QuestionnaireTopicOptions>)quesCache.get(quesId+QuestionnaireTopicService.QUES_TOPIC_OPT):null;
		if(optionsListTemp==null||optionsListTemp.size()==0) {
			optionsListTemp = optionDao.getOptionsByQuesIdAndOrder(quesId);
			if(isUsedCache) {
				quesCache.set(quesId+QuestionnaireTopicService.QUES_TOPIC_OPT, optionsListTemp);
			}
		}
//		LOGGER.error(userId+":user:op3:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
		List<String> topicOptions = new ArrayList<>();
		Map<String,List<QuestionnaireTopicOptions>> optionsMapListTemp= new HashMap<>();
		List<QuestionnaireTopicOptions> quesTopicOptListTemp=null;
		for(QuestionnaireTopicOptions quesTopicOpt:optionsListTemp) {
			//获取选项ids
			topicOptions.add(quesTopicOpt.getId());
			quesTopicOptListTemp=optionsMapListTemp.get(quesTopicOpt.getTopicId());
			//获取TopicId分组的选项列表
			if(quesTopicOptListTemp==null) {
				quesTopicOptListTemp=new ArrayList<>();
				optionsMapListTemp.put(quesTopicOpt.getTopicId(), quesTopicOptListTemp);
			}
			quesTopicOptListTemp.add(quesTopicOpt);
		}
//		List<String> topicOptions = optionsListTemp.stream().map(op->{return op.getId();}).collect(Collectors.toList());
		List<QuestionnaireAnswer> answersTemp=null;
		List<Map> optionsCountTemp=null;
		if(topicOptions.size()>0) {
			answersTemp=answerDao.getAnswerInfoByOptions(userId, topicOptions);
//			LOGGER.error(userId+":user:op4:"+(System.currentTimeMillis()-time));
//			time=System.currentTimeMillis();
			if(!isExam) {
				optionsCountTemp=getAnswerInfoCount(topicOptions);
			}
//			LOGGER.error(userId+":user:op4-1:"+(System.currentTimeMillis()-time));
//			time=System.currentTimeMillis();
		}
		for(int i=0;i<topicList.size();i++){
			QuestionnaireTopic topic = topicList.get(i);
			topic.setPage(StringUtils.null2String(pageIndex));
			if("paging".equals(topic.getTopicType())){
				String pageSetting = topic.getTopicSetting();
				Map<String,Object> mapTopicSet = new HashMap<String,Object>();
				mapTopicSet =  JsonUtils.readValue(pageSetting);
				topic.setPage(StringUtils.null2String(mapTopicSet.get("page")));
				pageIndex ++;
			}
			if(flag=="1"&&!"paging".equals(topic.getTopicType()) && !"illustrate".equals(topic.getTopicType())) {
				topic.setNumberOne("1");
				flag="0";
			}else {
				if("paging".equals(topic.getTopicType())||"illustrate".equals(topic.getTopicType())) {
					flag="1";
				}else if(!"paging".equals(topic.getTopicType()) && !"illustrate".equals(topic.getTopicType()) && i==0) {
					topic.setNumberOne("1");
				}else {
					topic.setNumberOne("0");
				}
			}
			
//			LOGGER.error(userId+":user:op5:"+(System.currentTimeMillis()-time));
//			time=System.currentTimeMillis();
			String ruleTopicName = topic.getTopicName();
			if(!"".equals(StringUtils.null2String(ruleTopicName))){
				//ruleTopicName =ruleTopicName.replace("<p>", "").replace("</p>", "");
				topic.setRuleTopicName(ruleTopicName);
			}
			String topicSetting =StringUtils.null2String(topic.getTopicSetting());
			if( !"".equals(topicSetting)){
				Map<String,Object> mapTopicSet = new HashMap<String,Object>();
				mapTopicSet =  JsonUtils.readValue(topicSetting);
				if("field".equals(topic.getTopicType())){
					String extensions = "";
					if("gif".equals(mapTopicSet.get("gif"))){
						extensions +="gif"+",";
					}
					if("png".equals(mapTopicSet.get("png"))){
						extensions +="png"+",";
					}
					if("jpg".equals(mapTopicSet.get("jpg"))){
						extensions +="jpg"+",";
					}
					if("jpeg".equals(mapTopicSet.get("jpeg"))){
						extensions +="jpeg"+",";
					}
					if("bmp".equals(mapTopicSet.get("bmp"))){
						extensions +="bmp"+",";
					}
					if("doc".equals(mapTopicSet.get("doc"))){
						extensions +="doc"+",";
					}
					if("docx".equals(mapTopicSet.get("docx"))){
						extensions +="docx"+",";
					}
					if("pdf".equals(mapTopicSet.get("pdf"))){
						extensions +="pdf"+",";
					}
					if("xls".equals(mapTopicSet.get("xls"))){
						extensions +="xls"+",";
					}
					if("xlsx".equals(mapTopicSet.get("xlsx"))){
						extensions +="xlsx"+",";
					}
					if("ppt".equals(mapTopicSet.get("ppt"))){
						extensions +="ppt"+",";
					}
					if("pptx".equals(mapTopicSet.get("pptx"))){
						extensions +="pptx"+",";
					}
					if("txt".equals(mapTopicSet.get("txt"))){
						extensions +="txt"+",";
					}
					if("rar".equals(mapTopicSet.get("rar"))){
						extensions +="rar"+",";
					}
					if("zip".equals(mapTopicSet.get("zip"))){
						extensions +="zip"+",";
					}
					if("gzip".equals(mapTopicSet.get("gzip"))){
						extensions +="gzip"+",";
					}
					if(extensions.endsWith(",")){
						extensions = extensions.substring(0, extensions.length()-1);
				    }
					if(!"".equals(extensions)){
						mapTopicSet.put("upload", "true");
					}else{
						mapTopicSet.put("upload", "false");
					}
					mapTopicSet.put("extensions", extensions);
				}
				topic.setSettingMap(mapTopicSet);
			}
//			LOGGER.error(userId+":user:op6:"+(System.currentTimeMillis()-time));
//			time=System.currentTimeMillis();
			//优化把查询数据库移动到了本方法开头，减少循环查询数据库次数
			List<QuestionnaireTopicOptions> optionsList = new ArrayList<>();
			if(optionsMapListTemp!=null) {
				optionsList=optionsMapListTemp.get(topic.getId());
			}
//			if(optionsListTemp!=null) {
//				for(QuestionnaireTopicOptions opTemp:optionsListTemp) {
//					if(topic.getId().equals(opTemp.getTopicId())) {
//						optionsList.add(opTemp);
//					}
//				}
//			}
//			LOGGER.error(userId+":user:op7:"+(System.currentTimeMillis()-time));
//			time=System.currentTimeMillis();
			//优化把查询数据库移动到了本方法开头，减少循环查询数据库次数
			List<QuestionnaireAnswer> answers= new ArrayList<>(); 
			if(answersTemp!=null) {
				for(QuestionnaireAnswer anTemp:answersTemp) {
					if(topic.getId().equals(anTemp.getTopicId())) {
						answers.add(anTemp);
					}
					
				}
			}
//			LOGGER.error(userId+":user:op8:"+(System.currentTimeMillis()-time));
//			time=System.currentTimeMillis();
			List<QuestionnaireTopicOptions> opList = new ArrayList<>();
			for(int j=0;j<optionsList.size();j++){
				QuestionnaireTopicOptions option = optionsList.get(j);
				int selectNum =0;
				if(optionsCountTemp!=null) {
					for(Map ele:optionsCountTemp) {
						if(option.getId().equals(ele.get("optionId"))) {
							String num = StringUtils.null2String(ele.get("num"));
							if(StringUtils.isNotBlank(num)) {
								selectNum=Integer.parseInt(num);
							}
							break;
						}
					}
				}
				//优化速度去掉此查询
//				int selectNum = getAnswerInfoCount(option.getId());//该选项选择人数
//				LOGGER.error(userId+":user:op9-1:"+(System.currentTimeMillis()-time));
//				time=System.currentTimeMillis();
				option.setSelectNum(selectNum);
				option.setTicketPercent(getPercent(selectNum, answerNum) + '%');//票数百分比
				QuestionnaireAnswer answer = null;
				if(answers!=null) {
					for(QuestionnaireAnswer answerTemp:answers) {
						if(option.getId().equals(answerTemp.getOptionId())) {
							answer=answerTemp;
							break;
						}
					}
//					LOGGER.error(userId+":user:op9-2:"+(System.currentTimeMillis()-time));
//					time=System.currentTimeMillis();
				}
				if(answer!=null && !"".equals(answer.getAnswer())){
					if("field".equals(topic.getTopicType())){
						String attachId = answer.getAnswer();
						String fileInfo =attchService.getAttachmentInfo(attachId,token);
			        	answer.setAttachment("["+fileInfo+"]");
					}
					if("check".equals(topic.getTopicType())){
						topic.setIsCheck("1");
					}
				}else{
//					try{
						if("check".equals(topic.getTopicType())){
							QuestionnaireAnswer answer1 = answerDao.getAnswerInfoByTopId(userId,topic.getId(), "");
							if(answer1 != null){
								topic.setIsCheck("-1");
							}
						}
//					}catch (Exception e){
//						LOGGER.error(e);
//					}

				}
				if(answer == null){
					answer = new QuestionnaireAnswer();
				}
				option.setAnswer(answer);
				String optionSet = StringUtils.null2String(option.getOptionSetting());
				if("mulscale".equals(topic.getTopicType())){
					if(!"".equals(optionSet)){
						List<String> mulList =Arrays.asList(optionSet.split("option-option")); 
						List<Map<String,Object>> mulscaleList = new ArrayList<Map<String,Object>>();
						for(int h=0;h<mulList.size();h++){
							Map<String,Object> mulscaleMap = new HashMap<String,Object>();
							mulscaleMap = JsonUtils.readValue(mulList.get(h));
							mulscaleList.add(mulscaleMap);
						}
						option.setList(mulscaleList);
					}
				}else{
					if(!"".equals(optionSet)){
						Map<String,Object> mapOptionSet = new HashMap<String,Object>();
						mapOptionSet =  JsonUtils.readValue(optionSet);
						option.setMapSet(mapOptionSet);
					}
				}
				int optionNo = option.getOptionOrder();
				if(optionNo !=0 ){
					option.setLetter(QuestionnaireUtils.getLetterByNum(optionNo));
				}
				opList.add(option);
			}
//			LOGGER.error(userId+":user:op9:"+(System.currentTimeMillis()-time));
//			time=System.currentTimeMillis();
			topic.setList(opList);
			list.add(topic);
		}
		int z = -1;
		List<Integer> qtoList ;
		Map<String,Object> mulscaleMap = new HashMap<String,Object>();
//		LOGGER.error(userId+":user:op10:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
		for(QuestionnaireTopic qt : list){
			z = -1;
			qtoList = new ArrayList<>();
			if(StringUtils.isNotBlank(qt.getTopicSetting())) mulscaleMap = JsonUtils.readValue(qt.getTopicSetting());
		    if(StringUtils.equals(QuestionnaireTopic.TopicTypeEnum.SCALE.getCode(),qt.getTopicType())
					&& StringUtils.equals("3",StringUtils.null2String(mulscaleMap.get("optionScale")))){
		    	boolean flags = false;
				for(QuestionnaireTopicOptions qto : qt.getList()){
					if(qto.getAnswer().getOptionId() != null){
						flags = true;
					}
					if(StringUtils.equals(qto.getAnswer().getOptionId(),qto.getId())){
						break;
					}
					z ++;
				}
				if(!flags){
					z = -1;
				}else{
					z ++;
				}
				qtoList.add(z);
				qt.setStarNum(qtoList);
				continue;
			}
			if(StringUtils.equals(QuestionnaireTopic.TopicTypeEnum.MULSCALE.getCode(),qt.getTopicType())
					&& StringUtils.equals("3",StringUtils.null2String(mulscaleMap.get("optionScale")))){
				for(QuestionnaireTopicOptions qto : qt.getList()){
					z = -1;
					if(qto.getAnswer().getAnswer() != null){
						z = 0;
					}else{
						qtoList.add(z);
						continue;
					}
					List<Map<String,Object>> mapList = qto.getList();
					for(Map<String,Object> mapL : mapList){
						if(qto.getAnswer().getAnswer() != null
						&& !StringUtils.equals(StringUtils.null2String(mapL.get("optionOrder")),qto.getAnswer().getAnswer())){
							z ++;
						}else{
							break;
						}
					}
					qtoList.add(z);
				}
				qt.setStarNum(qtoList);
				continue;
			}
		}
//		LOGGER.error(userId+":user:op11:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
		return list;
	}

	//获取百分比
	private String getPercent(int num, int total) {
		if(total != 0) {
			DecimalFormat df=new DecimalFormat("0");//设置保留位数
			float f = (float)num / total * 100;
			return df.format(f);
		}else {
			return "0";
		}
	}
	
	/**
	 *	根据问卷id 查询问卷题目数量
	 * @param quesId 问卷id
	 * @return  问卷题目数量
	 */
	public int getQuesTopic(String quesId){
		List<QuestionnaireTopic>  topicList = topicDao.getTopicByQeusId(quesId);
		if(CollectionUtils.isNotEmpty(topicList)){
			return topicList.size();
		}
		return 0;
	}
	
	/**
	 * 获取问卷题目信息
	 * @param quesId 问卷id
	 * @param num 答卷数量
	 * @param allUserNum 答卷总人数
	 * @return 问卷题目实体集合
	 */
	public List<QuestionnaireTopic> getStatistics(String quesId,int num,int allUserNum, String quesType){
		List<QuestionnaireTopic> list = new ArrayList<>();
		List<QuestionnaireTopic>  topicList = topicDao.getTopicByQeusId(quesId);
		for(int i=0;i<topicList.size();i++){
			QuestionnaireTopic topic = topicList.get(i);
			String ruleTopicName = topic.getTopicName();
			if(!"".equals(StringUtils.null2String(ruleTopicName))){
				ruleTopicName =ruleTopicName.replace("<p>", "").replace("</p>", "");
				topic.setRuleTopicName(ruleTopicName);
			}
			String topicSetting =StringUtils.null2String(topic.getTopicSetting());
			if( !"".equals(topicSetting)){
				Map<String,Object> mapTopicSet = new HashMap<String,Object>();
				mapTopicSet =  JsonUtils.readValue(topicSetting);
				topic.setSettingMap(mapTopicSet);
				topic.setTopicScore(StringUtils.null2String(mapTopicSet.get("topicScore")));
			}
			List<QuestionnaireTopicOptions> optionsList = optionDao.getOptionsByTopicId(topic.getId());
			List<QuestionnaireTopicOptions> opList = new ArrayList<>(); 
			/*题目的平均分*/
//			double allOptionScore =answerService.getTopicAnswerScore(topic.getId());
//			if("0".equals(topic.getIsScore())){
//				/*题目的总平均分*/
//				if(allUserNum !=0){ 
//					BigDecimal averageScore = new BigDecimal(allOptionScore/allUserNum);
//					averageScore = averageScore.setScale(2, RoundingMode.HALF_UP);
//					topic.setAverageScore(averageScore+"");
//				}else{
//					topic.setAverageScore("0.00");
//				}
//				/*真实平均值*/
//				if(num !=0){
//					BigDecimal realAverageScore = new BigDecimal(allOptionScore/num);
//					realAverageScore = realAverageScore.setScale(2, RoundingMode.HALF_UP);
//					topic.setRealAverageScore(realAverageScore+"");
//				}else{
//					topic.setRealAverageScore("0.00");
//				}
//			}
			for(int j=0;j<optionsList.size();j++){
				QuestionnaireTopicOptions option = optionsList.get(j);
				if("mulscale".equals(topic.getTopicType())){
					String optionSet = option.getOptionSetting();
					String[] mulStr = optionSet.split("option-option");
					List<Map<String,Object>> mulList = new ArrayList<Map<String,Object>>();
					for(int h=0;h<mulStr.length;h++){
						Map<String,Object> mulMap = JsonUtils.readValue(mulStr[h]);
						int optionNum = answerService.getMulScaleOptionNum(option.getId(),(String)mulMap.get("optionOrder"));
						double proportion =0;
						if(optionNum >0){
							proportion =((double)optionNum/num)*100;
							BigDecimal bg = new BigDecimal(proportion);
							proportion = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
						}
						mulMap.put("proportionStr", proportion);
						mulMap.put("proportion", proportion+"%");
						mulMap.put("optionNum", optionNum);
						mulList.add(mulMap);
					}
					option.setList(mulList);
				}else{
					Map<String,Object> map = new HashMap<String,Object>();
					int optionNum = answerService.getOptionNum(option.getId());
					double proportion =0;
					if(optionNum >0){
						proportion =((double)optionNum/num)*100;
						BigDecimal bg = new BigDecimal(proportion);
						proportion = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					}
					map.put("proportionStr", proportion);
					map.put("proportion", proportion+"%");
					map.put("optionNum", optionNum);
					option.setMapProp(map);
					String optionSet = StringUtils.null2String(option.getOptionSetting());
					if("mulscale".equals(topic.getTopicType())){
						if(!"".equals(optionSet)){
							List<String> mulList =Arrays.asList(optionSet.split("option-option")); 
							List<Map<String,Object>> mulscaleList = new ArrayList<Map<String,Object>>();
							for(int h=0;h<mulList.size();h++){
								Map<String,Object> mulscaleMap = new HashMap<String,Object>();
								mulscaleMap = JsonUtils.readValue(mulList.get(h));
								mulscaleList.add(mulscaleMap);
							}
							option.setList(mulscaleList);
						}
					}else{
						if(!"".equals(optionSet)){
							Map<String,Object> mapOptionSet = new HashMap<String,Object>();
							mapOptionSet = JsonUtils.readValue(optionSet);
							option.setMapSet(mapOptionSet);
						}
					}
					int optionNo = option.getOptionOrder();
					if(optionNo !=0 ){
						option.setLetter(QuestionnaireUtils.getLetterByNum(optionNo));
					}
				}
				opList.add(option);
			}
			topic.setList(opList);
			if("questionnaireExam".equals(quesType) && !"illustrate".equals(topic.getTopicType()) && !"paging".equals(topic.getTopicType())) {
				float fraction = topic.getTopicScore() != null ? Float.parseFloat(topic.getTopicScore()) : 0F;
				int rightNum = 0;
				if("fillInBlanks".equals(topic.getTopicType())) {
					List<Map> fractionList = answerService.getAnswerFractionByTopId(quesId, topic.getId());
					if(CollectionUtils.isNotEmpty(fractionList)) {
						for(Map m : fractionList) {
							String f = StringUtils.null2String(m.get("fraction"));
							if(StringUtils.isNotBlank(f) && Float.parseFloat(f) == fraction) rightNum++;
						}
					}
				}else {
					List<Map> userIdList = answerService.getAnswerRightUserIds(quesId, topic.getId(), fraction);
					if(CollectionUtils.isNotEmpty(userIdList)) rightNum = userIdList.size();
				}
				int answerNum = answerStatusDao.getAnswerNumByQuesId(quesId);//提交答卷人数
				topic.setAccuracy(getPercent(rightNum, answerNum) + '%');
			}
			list.add(topic);
		}
//		for(QuestionnaireTopic topic : list){
//			topic.setNum(0);
//
//			//问答题数量
//			if(StringUtils.equals(topic.getTopicType(),QuestionnaireTopic.TopicTypeEnum.ANSWER.getCode())){
//				topic.setNum(getAnswerTopicNum(QuestionnaireTopic.TopicTypeEnum.ANSWER.getCode(),quesId, QusetionnaireAnswerStatus.StatusEnum.SUBMIT.getCode(),topic.getId()));
//			}
//			//附件 数量
//			if(StringUtils.equals(topic.getTopicType(),QuestionnaireTopic.TopicTypeEnum.FIELD.getCode())){
//				topic.setNum(getAnswerTopicNum(QuestionnaireTopic.TopicTypeEnum.FIELD.getCode(),quesId, QusetionnaireAnswerStatus.StatusEnum.SUBMIT.getCode(),topic.getId()));
//			}
//			//填空题数量
//			if(StringUtils.equals(topic.getTopicType(),QuestionnaireTopic.TopicTypeEnum.FILLINBLANKS.getCode())){
//				topic.setNum(getAnswerTopicNum(QuestionnaireTopic.TopicTypeEnum.FILLINBLANKS.getCode(),quesId, QusetionnaireAnswerStatus.StatusEnum.SUBMIT.getCode(),topic.getId()));
//			}
//
//		}
		return list;
	}

	/**
	 * 查询问卷题目答题数量
	 * @param type 问卷类型
	 * @param quesId 问卷id
	 * @param status 答卷的状态
	 * @return
	 */
	private int getAnswerTopicNum(String type,String quesId,String status,String topicId){
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT DISTINCT oqas.createdBy FROM oa_qusetionnaire_answer_status oqas ");
		sql.append(" LEFT JOIN oa_questionnaire_answer oqa ON oqa.questionnaire_id = oqas.questionnaire_id");
		sql.append(" LEFT JOIN oa_questionnaire_topic oqt ON oqt.id = oqa.topic_id");
		sql.append(" WHERE oqt.topic_type = :type AND oqa.questionnaire_id = :id");
		sql.append(" AND oqas.status = :status AND oqa.answer IS NOT NULL and oqt.id = :topicid");
		if(GlobalConstant.isMySQL()){
			sql.append(" and oqa.answer != ''");
		}
		if(GlobalConstant.isOracle()){
			sql.append(" and DBMS_LOB.GETLENGTH(oqa.answer) <> 0");
		}
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("id", quesId);
		paramMap.put("type",type);
		paramMap.put("status",status);
		paramMap.put("topicid",topicId);
		List<Map> list = super.findByListNativeQuery(sql.toString(),"",paramMap);//query.getResultList();
		if(CollectionUtils.isNotEmpty(list)){
			return list.size();
		}
		return 0;
	}
	
	/**
	 * 获取问卷总分数
	 * @param quesId 问卷id
	 * @return 问卷总分数
	 */
	public int allQuesScore(String quesId){
		List<QuestionnaireTopicOptions> list = optionDao.getOptionsByQuesId(quesId);
		int score = 0;
		for(int i=0;i<list.size();i++){
			QuestionnaireTopicOptions option = list.get(i);
			String optionSet = option.getOptionSetting();
			Map<String,Object> map = JsonUtils.readValue(optionSet);
			String optionScore = (String)map.get("optionScore");
			if(!"".equals(StringUtils.null2String(optionScore))){
				score +=Integer.parseInt(optionScore);
			}
		}
		return score;
	}
	
	/**
	 * 查看答卷总人数
	 * @param quesId 问卷id
	 * @param token 系统参数：TOKEN
	 * @param corpId 单位ID
	 * @return 答卷总人数
	 */
	public int getQuestAnswerNum(String quesId,String token,String corpId){
		Questionnaire ques = quesService.findOne(quesId);
		if(ques == null){
			return 0;
		}
		String quesScope = ques.getQuestionnaireScope();
		List<String> scopeList = popService.getScopeValue("oa_questionnaire_scope","oa_questionnaire","questionnaire_scope",StringUtils.null2String(quesScope));
		String scopeStr ="";
		if(CollectionUtils.isNotEmpty(scopeList)){
			for(int i=0;i<scopeList.size();i++){
				scopeStr+=scopeList.get(i);
				if(i<scopeList.size()-1){
					scopeStr+=",";
				}
			}
		}
		List<String> userList = userApiService.getUserIdsByOrgId(scopeStr,"","1",corpId,token);
		userList.addAll(scopeList);
//		String ids="";
//		if(CollectionUtils.isNotEmpty(userList)){
//			for(int i=0;i<userList.size();i++){
//				ids+=userList.get(i);
//				if(i<userList.size()-1){
//					ids+=",";
//				}
//			}
//		}
		List<String> idList = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(userList)){
			String ids = "";
			for(int i=0;i<userList.size();i++){
				ids+=userList.get(i) + ",";
//				if(i<userList.size()-1){
//					ids+=",";
//				}
				if(ids.length() > 1000){
					idList.add(ids);
					ids = "";
				}
			}
			if(StringUtils.isNotBlank(ids)){
				idList.add(ids);
			}
		}
		int size = 0;
		List<Map<String,Object>> allList = new ArrayList<>();
		for(String ids : idList){
			allList = userApiService.getUserList(ids,corpId,"",token);
			if(CollectionUtils.isNotEmpty(allList)){
				size += allList.size();
			}
		}
//		if(CollectionUtils.isNotEmpty(allList)){
//			return allList.size();
//		}
//		return 0;
		return size;
	}
	
	
/*==========================================================================================*/
	
	/**
	 * 获取要保存的题目(钉钉)
	 * @param map 题目实体map形式
	 * @param quesitionnaireId 问卷ID
	 * @param topicType 题目类型：sinselect-单选、multiselect-多选、check-下拉、scale-量表、mulscale-矩阵量表、answer-问答、field-附件、paging-分页、illustrate-说明
	 * @return 题目实体集合
	 */
	public QuestionnaireTopic getDingSaveTopicInfo(Map<String,Object> map,String quesitionnaireId,String topicType){
		QuestionnaireTopic topic = new QuestionnaireTopic();
		String topicName = StringUtils.null2String(map.get("titleInfo"));
		String topicNameTxt = topicName;
		/*if(topicName == null || topicName == "") {
			topicName = (String) map.get("title");
			topicNameTxt = (String) map.get("title");
		}*/
		String topicNo = map.get("sortNo").toString();
		/*单选、多选、下拉、量表、矩阵量表有是否计分选项*/
		if("sinselect".equals(topicType) || "multiselect".equals(topicType) || "check".equals(topicType) || "scale".equals(topicType) || "mulscale".equals(topicType)){
			String isScore =  map.get("isScore")== null?"0":(String)map.get("isScore");
			topic.setIsScore(isScore);
		}
		if("illustrate".equals(topicType) || "paging".equals(topicType)){
			topicNo="";
		}else{
			Map<String,Object> topicMap = (Map<String, Object>) map.get("topicSetting");
			String topicSetting =JsonUtil.mapToJson(topicMap);
			topic.setTopicSetting(topicSetting);
		}
		int orderNo = 0;
		if(map.get("dataSort") != null){
			orderNo = Integer.parseInt(map.get("dataSort").toString());
		}
		
		topic.setTopicName(topicName);
		topic.setTopicNameTxt(topicNameTxt);
		topic.setTopicNo(topicNo);
		topic.setOrderNo(orderNo);
		topic.setTopicType(topicType);
		topic.setCreatedDate(new Date());
		topic.setQuestionnaireId(quesitionnaireId);
		String id = UuidUtils.UUID();
		topic.setId(id);
		return topic;
	}
	
	
	/**
	 * 获取问卷题目信息
	 * @param quesId 问卷ID
	 * @param userId 用户ID
	 * @Param isAnswer 展示答案状态位   “1” 展示答案
	 * @param token 系统参数：TOKEN
	 * @return 问卷题目实体集合
	 */
	public List<QuestionnaireTopic> getDingTopicOPtionInfo(String quesId,String userId,String isAnswer,String token){
		List<QuestionnaireTopic> list = new ArrayList<>();
		List<QuestionnaireTopic>  topicList = topicDao.getTopicByQeusId(quesId);
		List<String> illustrateList = new ArrayList<>();
		List<String> illustrateTxtList = new ArrayList<>();
		int pageIndex = 1;
		for(int i=0;i<topicList.size();i++){
			QuestionnaireTopic topic = topicList.get(i);
			topic.setPage(StringUtils.null2String(pageIndex));
			if("paging".equals(topic.getTopicType())){
				pageIndex ++;
			}
			String ruleTopicName = topic.getTopicName();
			if(!"".equals(StringUtils.null2String(ruleTopicName))){
				ruleTopicName =ruleTopicName.replace("<p>", "").replace("</p>", "");
				topic.setRuleTopicName(ruleTopicName);
			}
			String topicSetting =StringUtils.null2String(topic.getTopicSetting());
			if( !"".equals(topicSetting)){
				Map<String,Object> mapTopicSet = new HashMap<String,Object>();
				mapTopicSet =  JsonUtils.readValue(topicSetting);
				if("field".equals(topic.getTopicType())){
					String extensions = "";
					if("gif".equals(mapTopicSet.get("gif"))){
						extensions +="gif"+",";
					}
					if("png".equals(mapTopicSet.get("png"))){
						extensions +="png"+",";
					}
					if("jpg".equals(mapTopicSet.get("jpg"))){
						extensions +="jpg"+",";
					}
					if("jpeg".equals(mapTopicSet.get("jpeg"))){
						extensions +="jpeg"+",";
					}
					if("bmp".equals(mapTopicSet.get("bmp"))){
						extensions +="bmp"+",";
					}
					if("doc".equals(mapTopicSet.get("doc"))){
						extensions +="doc"+",";
					}
					if("docx".equals(mapTopicSet.get("docx"))){
						extensions +="docx"+",";
					}
					if("pdf".equals(mapTopicSet.get("pdf"))){
						extensions +="pdf"+",";
					}
					if("xls".equals(mapTopicSet.get("xls"))){
						extensions +="xls"+",";
					}
					if("xlsx".equals(mapTopicSet.get("xlsx"))){
						extensions +="xlsx"+",";
					}
					if("ppt".equals(mapTopicSet.get("ppt"))){
						extensions +="ppt"+",";
					}
					if("pptx".equals(mapTopicSet.get("pptx"))){
						extensions +="pptx"+",";
					}
					if("txt".equals(mapTopicSet.get("txt"))){
						extensions +="txt"+",";
					}
					if("rar".equals(mapTopicSet.get("rar"))){
						extensions +="rar"+",";
					}
					if("zip".equals(mapTopicSet.get("zip"))){
						extensions +="zip"+",";
					}
					if("gzip".equals(mapTopicSet.get("gzip"))){
						extensions +="gzip"+",";
					}
					if(extensions.endsWith(",")){
						extensions = extensions.substring(0, extensions.length()-1);
				    }
					if(!"".equals(extensions)){
						mapTopicSet.put("upload", "true");
					}else{
						mapTopicSet.put("upload", "false");
					}
					mapTopicSet.put("extensions", extensions);
				}
				topic.setSettingMap(mapTopicSet);
			}
			if(i==topicList.size()-1 && "illustrate".equals(topic.getTopicType())) {
				topic.setIllustrateList(illustrateList);
				illustrateList=new ArrayList<>();
				topic.setIllustrateTxtList(illustrateTxtList);
				illustrateTxtList=new ArrayList<>();
			}else {
				if("illustrate".equals(topic.getTopicType())) {
					illustrateList.add(topic.getTopicName());
					illustrateTxtList.add(topic.getTopicNameTxt());
				}else if(!"paging".equals(topic.getTopicType())){
					topic.setIllustrateList(illustrateList);
					illustrateList=new ArrayList<>();
					topic.setIllustrateTxtList(illustrateTxtList);
					illustrateTxtList=new ArrayList<>();
				}
			}
			List<QuestionnaireTopicOptions> optionsList = optionDao.getOptionsByTopicId(topic.getId());
			List<QuestionnaireTopicOptions> opList = new ArrayList<>(); 
			for(int j=0;j<optionsList.size();j++){
				QuestionnaireTopicOptions option = optionsList.get(j);
				QuestionnaireAnswer answer = null;
				//根据状态位  是否展示答案
				if(StringUtils.isNotBlank(isAnswer) && StringUtils.equals("1",isAnswer)){
					int selectNum = getAnswerInfoCount(option.getId());//该选项选择人数
					int answerNum = answerStatusDao.getAnswerNumByQuesId(quesId);//提交答卷人数
					option.setSelectNum(selectNum);
					option.setTicketPercent(getPercent(selectNum, answerNum) + '%');//票数百分比
					answer = answerDao.getAnswerInfo(userId, option.getId());
					if(answer!=null && !"".equals(answer.getAnswer())){
						if("field".equals(topic.getTopicType())){
							String attachId = answer.getAnswer();
							String fileInfo =attchService.getAttachmentInfo(attachId,token);
							answer.setAttachment("["+fileInfo+"]");
						}
						if("check".equals(topic.getTopicType())){
							topic.setIsCheck("1");
						}
					}else{
						if("check".equals(topic.getTopicType())){
							QuestionnaireAnswer answer1 = answerDao.getAnswerInfoByTopId(userId,topic.getId(), "");
							if(answer1 != null){
								topic.setIsCheck("-1");
							}
						}
					}
				}
				if(answer == null){
					answer = new QuestionnaireAnswer();
				}
				option.setAnswer(answer);
				String optionSet = StringUtils.null2String(option.getOptionSetting());
				if("mulscale".equals(topic.getTopicType())){
					if(!"".equals(optionSet)){
						List<String> mulList =Arrays.asList(optionSet.split("option-option")); 
						List<Map<String,Object>> mulscaleList = new ArrayList<Map<String,Object>>();
						for(int h=0;h<mulList.size();h++){
							Map<String,Object> mulscaleMap = new HashMap<String,Object>();
							mulscaleMap = JsonUtils.readValue(mulList.get(h));
							mulscaleList.add(mulscaleMap);
						}
						option.setList(mulscaleList);
					}
				}else{
					if(!"".equals(optionSet)){
						Map<String,Object> mapOptionSet = new HashMap<String,Object>();
						mapOptionSet =  JsonUtils.readValue(optionSet);
						option.setMapSet(mapOptionSet);
					}
				}
				int optionNo = option.getOptionOrder();
				if(optionNo !=0 ){
					option.setLetter(QuestionnaireUtils.getLetterByNum(optionNo));
				}
				opList.add(option);
			}
			topic.setList(opList);
			if("illustrate".equals(topic.getTopicType())&&i==topicList.size()-1) {
				list.add(topic);
			}else if(!"paging".equals(topic.getTopicType()) && !"illustrate".equals(topic.getTopicType())) {
				list.add(topic);
			}
		}
		return list;
	}

	/**
	 * 该选项选择人数
	 * @param optionId
	 * @return
	 */
	public int getAnswerInfoCount(String optionId) {
		StringBuffer sql = new StringBuffer();
		sql.append("select count(1) num from oa_questionnaire_answer oqa, oa_qusetionnaire_answer_status oqas ");
		sql.append(" where oqa.questionnaire_id=oqas.questionnaire_id and oqa.user_id=oqas.createdBy and oqas.status='1' and oqa.option_id=:optionId");
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("optionId", optionId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "", paramMap);
		if(CollectionUtils.isNotEmpty(list)){
			String num = StringUtils.null2String(list.get(0).get("num"));
			if(StringUtils.isNotBlank(num)) return Integer.parseInt(num);
		}
		return 0;
	}
	
	/**
	 * 对应选项选择人数
	 * @param optionIds
	 * @return
	 */
	public List<Map> getAnswerInfoCount(List<String> optionIds) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT" + 
				"	oqa.option_id optionId," + 
				"	count(1) num " + 
				"FROM" + 
				"	oa_questionnaire_answer oqa," + 
				"	oa_qusetionnaire_answer_status oqas " + 
				"WHERE " + 
				"	oqa.questionnaire_id = oqas.questionnaire_id " + 
				"AND oqa.user_id = oqas.createdBy " + 
				"AND oqas. STATUS = '1' " + 
				"AND oqa.option_id IN(:optionIds) "+
				"GROUP BY oqa.option_id");
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("optionIds", optionIds);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "", paramMap);
		if(CollectionUtils.isEmpty(list)){
			list=new ArrayList<>(0);
		}
		return list;
	}
	
	/**
	 * 根据Id删除题目
	 * 
	 * @param topicId
	 */
	public void deleteTopicById(String topicId) {
		this.topicDao.deleteTopicByTopicId(topicId);
	}
	
	/**
	 * 解析excel表格处理不同的题型
	 * @param sheet
	 * @param quetype
	 * @param questionnaireId
	 * @return
	 */
	public OperationResult resolveSheet(Sheet sheet, String quetype,String questionnaireId) {
		List<QuestionnaireTopic> listTopic = new ArrayList<QuestionnaireTopic>();
    	List<QuestionnaireTopicOptions> listOptions = new ArrayList<QuestionnaireTopicOptions>();
    	int lastNum=sheet.getLastRowNum();
    	Map<String,Object>i18nKey=new HashMap<>(1);
    	int sumScore=0,sumTopicNum=0,optionLimitLength=20;
		for(int rownum=1;rownum<lastNum+1;rownum++) {
			String times=UuidUtils.UUID();
			CellRangeAddress rowRange =getMergerCellRegionRow(sheet,rownum,1);
			int firstRow=rownum;
			if(rowRange!=null) {
				firstRow=rowRange.getFirstRow();
				rownum=rowRange.getLastRow();
			}
			Row row=sheet.getRow(firstRow);
			if(this.isRowEmpty(row)) {
				continue;
			}
			//题目编号为空
			if(row.getCell(0)==null||StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查题目编号不能为空");
			}
			String topicNo=row.getCell(0).getStringCellValue();//题目编号
			String name=row.getCell(1).getStringCellValue();//题目标题
			if(StringUtils.isBlank(name)) {
				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查题目不能为空");
			}
			String topicType=StringUtils.trimToEmpty(row.getCell(2).getStringCellValue());//题目题型
			if(StringUtils.isBlank(topicType)) {
				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查题目题型不能为空");
			}
			Map<String,Object> topicAllSettingMap =new HashMap<>();
			Map<String,Object> topicSettingMap =new HashMap<>();
			if(quetype=="0") {
				topicSettingMap.put("willAnswer", "1");
				topicSettingMap.put("optionScale", "1");
				topicAllSettingMap.put("times", times);
				topicAllSettingMap.put("topic", "<p id='initContent'>"+name+"</p>");
				topicAllSettingMap.put("topicTxt", name);
				topicAllSettingMap.put("isScore", "0");
				topicAllSettingMap.put("topicNo", topicNo);
				topicAllSettingMap.put("dataSortNo", topicNo);
				topicAllSettingMap.put("topicSetting", topicSettingMap);
				QuestionnaireTopic topic = new QuestionnaireTopic();
				String optionSetting="",optionChildSetting="";
				if("矩阵量表".equals(topicType)) {
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "mulscale");
	    			listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell4=sheet.getRow(i).getCell(4)!=null?sheet.getRow(i).getCell(4).getStringCellValue():"";
	    				if(!optionCheck(cell4,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell4)) {
	    					optionNum++;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell4+"\"}option-option");
	    				}
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项矩阵量表横标题至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			sb.setLength(0);
	    			optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell5=sheet.getRow(i).getCell(5)!=null?sheet.getRow(i).getCell(5).getStringCellValue():"";
	    				if(!optionCheck(cell5,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell5)) {
	    					optionNum++;
	    					sb.append("{\"optionChildOrder\":\""+opn+"\",\"childOption\":\""+cell5+"\",\"optionScore\":\"1\",\"optionOrder\":\""+(opn-1)+"\"}option-option");
	    				}
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项矩阵量表纵标题至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionChildSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, optionChildSetting,topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("量表".equals(topicType)) {
					topicSettingMap.put("optionScale", "2");
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "scale");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"optionScore\":\""+opn+"\"}}option-option");
	    				}
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+firstRow+"行:请检查该题选项至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("普通单选".equals(topicType)) {
					topicSettingMap.remove("optionScale");
					topicSettingMap.put("ezQuABC", "0");
					topicSettingMap.put("optionArray", "1");
					topicSettingMap.put("topicScore", "0");
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "sinselect");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"optionBlank\":\"0\",\"isRightAnswer\":\"\"}}option-option");
	    				}
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("普通多选".equals(topicType)) {
					topicSettingMap.remove("optionScale");
					topicSettingMap.put("ezQuABC", "0");
					topicSettingMap.put("optionArray", "1");
					topicSettingMap.put("minMultiselect", "2");
					topicSettingMap.put("maxMultiselect", "2");
					topicSettingMap.put("topicScore", "0");
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "multiselect");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"optionBlank\":\"0\",\"isRightAnswer\":\"\"}}option-option");
	    				}
	    			}
	    			if(optionNum<2) {
	    				return OperationResult.buildFailureResult("第"+firstRow+"行:请检查该题选项至少要有两个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("下拉框".equals(topicType)) {
					topicSettingMap.remove("optionScale");
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "check");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"optionDefault\":\"0\",\"optionScore\":\"0\"}}option-option");
	    				}
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("上传附件".equals(topicType)) {
					topicSettingMap.remove("optionScale");
					topicSettingMap.put("fieldMaxM", "1");
					topicSettingMap.put("fieldMaxNum", "1");
					topicSettingMap.put("topicScore", "0");
					topicSettingMap.put("quRestrict", "0");
					topicSettingMap.put("picall", "1");
					topicSettingMap.put("gif", "gif");
					topicSettingMap.put("png", "png");
					topicSettingMap.put("jpg", "jpg");
					topicSettingMap.put("jpeg", "jpeg");
					topicSettingMap.put("bmp", "bmp");
					topicSettingMap.put("docall", "1");
					topicSettingMap.put("doc", "doc");
					topicSettingMap.put("docx", "docx");
					topicSettingMap.put("pdf", "pdf");
					topicSettingMap.put("xls", "xls");
					topicSettingMap.put("xlsx", "xlsx");
					topicSettingMap.put("ppt", "ppt");
					topicSettingMap.put("pptx", "pptx");
					topicSettingMap.put("txt", "txt");
					topicSettingMap.put("compall", "1");
					topicSettingMap.put("rar", "rar");
					topicSettingMap.put("zip", "zip");
					topicSettingMap.put("gzip", "gzip");
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "field");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					sb.append("{\"filedId\":\"12345666\"}");
	    				}
	    			}
	    			optionSetting=sb.toString();
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("单项填空".equals(topicType)) {
					topicSettingMap.remove("optionScale");
					topicSettingMap.put("topicScore", "0");
					topicSettingMap.put("answer", "");
					topicAllSettingMap.put("topicSetting", JsonUtils.writeValueAsString(topicSettingMap));
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "answer");
					listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("多项填空".equals(topicType)) {
					topicSettingMap.remove("optionScale");
					topicSettingMap.put("topicScore", "0");
					topicSettingMap.put("quUnderline", "0");
					topicAllSettingMap.put("topicSetting", JsonUtils.writeValueAsString(topicSettingMap));
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "fillInBlanks");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"charType\":\"int\",\"blankLength\":\"1\",\"optionRequired\":\"1\",\"score\":\"0\",\"answer\":\"\"}}option-option");
	    				}
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
			}
			if(quetype=="1") {
				topicSettingMap.put("willAnswer", "1");
				topicAllSettingMap.put("times", times);
				topicAllSettingMap.put("topic", "<p id='initContent'>"+name+"</p>");
				topicAllSettingMap.put("topicTxt", name);
				topicAllSettingMap.put("isScore", "0");
				topicAllSettingMap.put("topicNo", topicNo);
				topicAllSettingMap.put("dataSortNo", topicNo);
				topicAllSettingMap.put("topicSetting", topicSettingMap);
				QuestionnaireTopic topic = new QuestionnaireTopic();
				String optionSetting="";
				if("投票单选".equals(topicType)) {
					topicSettingMap.put("ezQuABC", "0");
					topicSettingMap.put("optionArray", "1");
					topicSettingMap.put("topicScore", "0");
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "sinselect");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"optionBlank\":\"0\",\"isRightAnswer\":\"\"}}option-option");
	    				}
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("投票多选".equals(topicType)) {
					topicSettingMap.put("ezQuABC", "0");
					topicSettingMap.put("optionArray", "1");
					topicSettingMap.put("minMultiselect", "2");
					topicSettingMap.put("maxMultiselect", "2");
					topicSettingMap.put("topicScore", "0");
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "multiselect");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"optionBlank\":\"0\",\"isRightAnswer\":\"\"}}option-option");
	    				}
	    			}
	    			if(optionNum<2) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项至少要有两个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
			}
			if(quetype=="2") {
				topicSettingMap.put("willAnswer", "1");
				topicAllSettingMap.put("times", times);
				topicAllSettingMap.put("topic", "<p id='initContent'>"+name+"</p>");
				topicAllSettingMap.put("topicTxt", name);
				topicAllSettingMap.put("isScore", "0");
				topicAllSettingMap.put("topicNo", topicNo);
				topicAllSettingMap.put("dataSortNo", topicNo);
				topicAllSettingMap.put("topicSetting", topicSettingMap);
				QuestionnaireTopic topic = new QuestionnaireTopic();
				String optionSetting="",optionChildSetting="";
				if("考试单选".equals(topicType)) {
					topicSettingMap.put("ezQuABC", "0");
					topicSettingMap.put("optionArray", "1");
					topicSettingMap.put("topicScore", "5");
					sumTopicNum++;
					sumScore+=5;
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "sinselect");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int isRightAnswer=0,rightAnswerNum=0;
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				String rightAnswer=sheet.getRow(i).getCell(4)!=null?sheet.getRow(i).getCell(4).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					if(StringUtils.isNotBlank(rightAnswer)&&"是".equals(rightAnswer)) {
	    						rightAnswerNum++;
	    						if(isRightAnswer==1) {
	    							i18nKey.put("i18NCode", "oa.que.onlyhasoneanswer");
	    							i18nKey.put("prefix", topicNo+":");
	    							return OperationResult.buildFailureResult( topicNo+":只能有一个正确答案", i18nKey);
	    						}
	    						isRightAnswer=1;
	    					}else isRightAnswer=0;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"optionBlank\":\"\",\"isRightAnswer\":\""+isRightAnswer+"\"}}option-option");
	    				}
	    			}
	    			if(rightAnswerNum==0) {
	    				i18nKey.put("i18NCode", "oa.que.notsetrightanswer");
	    				i18nKey.put("prefix", topicNo+":");
						return OperationResult.buildFailureResult(topicNo+":未设置正确答案", i18nKey);
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("考试多选".equals(topicType)) {
					topicSettingMap.put("ezQuABC", "0");
					topicSettingMap.put("optionArray", "1");
					topicSettingMap.put("minMultiselect", "2");
					topicSettingMap.put("maxMultiselect", "2");
					topicSettingMap.put("topicScore", "5");
					sumTopicNum++;
					sumScore+=5;
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "multiselect");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int isRightAnswer=0,rightAnswerNum=0;
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				String rightAnswer=sheet.getRow(i).getCell(4)!=null?sheet.getRow(i).getCell(4).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					if(StringUtils.isNotBlank(rightAnswer)&&"是".equals(rightAnswer)) {
	    						rightAnswerNum++;
	    						isRightAnswer=1;
	    					}else isRightAnswer=0;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"optionBlank\":\"\",\"isRightAnswer\":\""+isRightAnswer+"\"}}option-option");
	    				}
	    			}
	    			if(rightAnswerNum==0) {
	    				i18nKey.put("i18NCode", "oa.que.notsetrightanswer");
	    				i18nKey.put("prefix", topicNo+":");
						return OperationResult.buildFailureResult(topicNo+":未设置正确答案", i18nKey);
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("考试判断".equals(topicType)) {
					topicSettingMap.put("topicScore", "5");
					sumTopicNum++;
					sumScore+=5;
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "trueOrFalse");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			int isRightAnswer=0,rightAnswerNum=0;
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				Cell rcell3=sheet.getRow(i).getCell(3);
	    				String cell3=rcell3!=null?rcell3.getStringCellValue():"";
	    				Cell cell4=sheet.getRow(i).getCell(4);
	    				String rightAnswer=cell4!=null?cell4.getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					if(StringUtils.isNotBlank(rightAnswer)&&"是".equals(rightAnswer)) {
	    						rightAnswerNum++;
	    						isRightAnswer=1;
	    					}else isRightAnswer=0;
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"isRightAnswer\":\""+isRightAnswer+"\"}}option-option");
	    				}
	    			}
	    			if(rightAnswerNum==0) {
	    				i18nKey.put("i18NCode", "oa.que.notsetrightanswer");
	    				i18nKey.put("prefix", topicNo+":");
						return OperationResult.buildFailureResult(topicNo+":未设置正确答案", i18nKey);
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项至少要有一个");
	    			}
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("单项填空".equals(topicType)) {
					topicSettingMap.put("topicScore", "5");
					sumTopicNum++;
					sumScore+=5;
					String rightAnswer=sheet.getRow(firstRow).getCell(4)!=null?sheet.getRow(firstRow).getCell(4).getStringCellValue():"";
					if(StringUtils.isBlank(rightAnswer)) {
						i18nKey.put("i18NCode", "oa.que.notsetrightanswer");
						i18nKey.put("prefix", topicNo+":");
						return OperationResult.buildFailureResult(topicNo+":未设置正确答案", i18nKey);
					}
					topicSettingMap.put("answer", rightAnswer);
					topicAllSettingMap.put("topicSetting", JsonUtils.writeValueAsString(topicSettingMap));
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "answer");
					listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("多项填空".equals(topicType)) {
					topicSettingMap.put("quUnderline", "");
	    			StringBuffer sb=new StringBuffer();
	    			int rightAnswerNum=0,topicNum=0;
	    			int optionNum=0;
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				String rightAnswer=sheet.getRow(i).getCell(4)!=null?sheet.getRow(i).getCell(4).getStringCellValue():"";
	    				if(!optionCheck(cell3,optionLimitLength)) {
	    					return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项字符长度不能超过限定值"+optionLimitLength);
	    				}
	    				if(StringUtils.isNotBlank(cell3)) {
	    					optionNum++;
	    					topicNum++;
	    					if(StringUtils.isNotBlank(rightAnswer)) {
	    						rightAnswerNum++;
	    					}
	    					sb.append("{\"optionOrder\":\""+opn+"\",\"option\":\""+cell3+"\",\"optionSetting\":{\"charType\":\"\",\"blankLength\":\"\",\"optionRequired\":\"\",\"score\":\"5\",\"answer\":\""+rightAnswer+"\"}}option-option");
	    				}
	    			}
	    			if(rightAnswerNum==0) {
	    				i18nKey.put("i18NCode", "oa.que.notsetrightanswer");
	    				i18nKey.put("prefix", topicNo+":");
						return OperationResult.buildFailureResult(topicNo+":未设置正确答案", i18nKey);
	    			}
	    			if(optionNum!=rightAnswerNum) {
	    				return OperationResult.buildFailureResult(topicNo+":每个填空项的答案为必填项");
	    			}
	    			if(optionNum==0) {
	    				return OperationResult.buildFailureResult("第"+(firstRow+1)+"行:请检查该题选项至少要有一个");
	    			}
	    			topicSettingMap.put("topicScore", 5*topicNum);
	    			sumTopicNum++;
	    			sumScore+=5*topicNum;
					topicAllSettingMap.put("topicSetting", JsonUtils.writeValueAsString(topicSettingMap));
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "fillInBlanks");
					listTopic.add(topic);
	    			if(sb.length()>13) {
	    				optionSetting=sb.substring(0,sb.length()-13);
	    			}
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("考试简答".equals(topicType)) {
					topicSettingMap.put("topicScore", "5");
					sumTopicNum++;
					sumScore+=5;
					topicSettingMap.put("answer", "");
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "shortAnswer");
					listTopic.add(topic);
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
				if("考试文件".equals(topicType)) {
					topicSettingMap.put("fieldMaxM", "1");
					topicSettingMap.put("fieldMaxNum", "1");
					topicSettingMap.put("topicScore", "5");
					sumTopicNum++;
					sumScore+=5;
					topicSettingMap.put("quRestrict", "0");
					topicSettingMap.put("picall", "1");
					topicSettingMap.put("gif", "gif");
					topicSettingMap.put("png", "png");
					topicSettingMap.put("jpg", "jpg");
					topicSettingMap.put("jpeg", "jpeg");
					topicSettingMap.put("bmp", "bmp");
					topicSettingMap.put("docall", "1");
					topicSettingMap.put("doc", "doc");
					topicSettingMap.put("docx", "docx");
					topicSettingMap.put("pdf", "pdf");
					topicSettingMap.put("xls", "xls");
					topicSettingMap.put("xlsx", "xlsx");
					topicSettingMap.put("ppt", "ppt");
					topicSettingMap.put("pptx", "pptx");
					topicSettingMap.put("txt", "txt");
					topicSettingMap.put("compall", "1");
					topicSettingMap.put("rar", "rar");
					topicSettingMap.put("zip", "zip");
					topicSettingMap.put("gzip", "gzip");
					topicAllSettingMap.put("topicSetting", topicSettingMap);
					topic = this.getSaveTopicInfo(topicAllSettingMap, questionnaireId, "field");
					listTopic.add(topic);
	    			StringBuffer sb=new StringBuffer();
	    			for(int opn=1,i=firstRow;i<rownum+1;opn++,i++) {
	    				String cell3=sheet.getRow(i).getCell(3)!=null?sheet.getRow(i).getCell(3).getStringCellValue():"";
	    				if(StringUtils.isNotBlank(cell3)) {
	    					sb.append("{\"filedId\":\"12345666\"}");
	    				}
	    			}
	    			optionSetting=sb.toString();
	    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
	    			listOptions.addAll(listOption);
				}
			}
			
		}
		Questionnaire entity = questionnaireService.findOne(questionnaireId);
    	if(entity != null) {
    		if(StringUtils.isNotBlank(entity.getSumScore())&&StringUtils.isNotBlank(entity.getSumTopicNum())){
    			entity.setSumScore(String.valueOf(Long.valueOf(entity.getSumScore())+Long.valueOf(sumScore)));
    			entity.setSumTopicNum(String.valueOf(Long.valueOf(entity.getSumTopicNum())+Long.valueOf(sumTopicNum)));
    		}else {
    			entity.setSumScore(sumScore+"");
        		entity.setSumTopicNum(sumTopicNum+"");
    		}
    		
    		questionnaireService.save(entity);
//    		List<String> topicList = this.getTopicIdByQeusId(questionnaireId);
//    		optionService.deleteOptionsByTopicId(topicList);
//    		this.deleteTopicByQuesId(questionnaireId);
        	List<String> queIdsList = new ArrayList<>();
        	queIdsList.add(questionnaireId);
    		answerService.deleteAnswerByQuesId(queIdsList);
    		questionnaireAnswerStatusService.deleteStatusByQuesId(queIdsList);
    		for(QuestionnaireTopic t:listTopic) {
    			System.out.println(t.getTopicName()+":"+t.getQuestionnaireId());
    		}
    		this.save(listTopic);
        	optionService.save(listOptions);
    		questionnaireService.setQuesSendN(questionnaireId);
    		questionnaireService.updateQuesMobile(questionnaireId,"","0");
    		}
		return null;
	}
	
	/**
	 * 获取指定单元格是不是合并单元格如果是则返回
	 * @param sheet
	 * @param cellRow
	 * @param cellCol
	 * @return
	 */
	private CellRangeAddress getMergerCellRegionRow(Sheet sheet, int cellRow, int cellCol){
		 CellRangeAddress retVal = null;
	    int sheetMergerCount = sheet.getNumMergedRegions();
	    for (int i = 0; i < sheetMergerCount; i++) {
	        CellRangeAddress cra = sheet.getMergedRegion(i);
	        int firstRow = cra.getFirstRow(); // 合并单元格CELL起始行
	        int firstCol = cra.getFirstColumn(); // 合并单元格CELL起始列
	        int lastRow = cra.getLastRow(); // 合并单元格CELL结束行
	        int lastCol = cra.getLastColumn(); // 合并单元格CELL结束列
	        if (cellRow >= firstRow && cellRow <= lastRow) { // 判断该单元格是否是在合并单元格中
	            if (cellCol >= firstCol && cellCol <= lastCol) {
	                retVal = cra; // 得到合并的行数
	                break;
	            }
	        }
	    }
	    return retVal;
	}
	
	private boolean optionCheck(String option,int limit) {
		if(option!=null&&option.length()>limit) {
			return false;
		}
		return true;
	}
	
	public boolean isRowEmpty(Row row) {
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            Cell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                return false;
            }
        }
        return true;
    }
}
